<?php


namespace app\user\controller;


use app\BaseController;
use app\common\exception\CaptchaException;
use app\common\exception\ClientException;
use app\common\exception\NotFundException;
use app\common\tool\CacheTool;
use app\common\tool\QQEmail;
use app\common\tool\StrTool;
use app\model\Discuss;
use app\model\User as UserModel;
use app\user\service\LoginService;
use think\exception\ValidateException;

class User extends BaseController
{
    public function login()
    {
        $param = $this->request->param(['email', 'password', 'email_captcha']);

        try {
            $this->validate($param, 'UserValidate.login');
        } catch (ValidateException $e) {
            throw new ClientException(['msg' => $e->getMessage()]);
        }

        $check_result = (new CacheTool)->checkCache(config('secure.captcha_key'), $param['email_captcha']);

        if (!$check_result) {
            throw new CaptchaException();
        } else {
            (new CacheTool())->clearCache(config('secure.captcha_key'));
        }

        $user = UserModel::where('email', '=', $param['email'])->find();
        if (!$user) {
            throw new NotFundException(['msg' => '用户不存在']);
        }

        $check_result = $user->check_pwd($param['password']);
        if (!$check_result) {
            throw new ClientException(['msg' => '密码错误']);
        }

        return (new LoginService())->save_return_jwt($user->id);
    }

    public function register()
    {
        $param = $this->request->param(['name', 'email', 'password', 'email_captcha']);

        try {
            $this->validate($param, 'UserValidate.register');
        } catch (ValidateException $e) {
            throw new ClientException(['msg' => $e->getMessage()]);
        }

        $check_result = (new CacheTool)->checkCache(config('secure.captcha_key'), $param['email_captcha']);

        if (!$check_result) throw new CaptchaException();

        $salt = StrTool::round_captcha(6, 4);
        $param['password'] = (new UserModel())->encryption_pwd($salt, $param['password']);
        $param['salt'] = $salt;

        UserModel::create($param);
    }

    public function email()
    {
        $qq_email = $this->request->param('email');
        $name = $this->request->param('name');
        $type = $this->request->param('type', 0);

        $param = [
            'email' => $qq_email,
            'name' => $name,
            'type' => $type
        ];

        try {
            $validate_type = $type ? 'UserValidate.sendEmail_register' : 'UserValidate.sendEmail_login';
            $this->validate($param, $validate_type);
        } catch (ValidateException $e) {
            throw new ValidateException(['msg' => $e->getMessage()]);
        }

        $this->isExistEmail($qq_email, $type);

        $email = new QQEmail();
        $email->sendMailtoUser($qq_email, $name);
    }

    protected function isExistEmail($email, $type = 0)
    {
        $verify_type = ['login', 'register'];

        if ($verify_type[$type] == 'register') {
            $user = UserModel::where('email', '=', $email)->count();
            if ($user) throw new ClientException(['msg' => '此邮箱号已经被注册']);
        }

        if ($verify_type[$type] == 'login') {
            $user = UserModel::where('email', '=', $email)->find();
            if (!$user) throw new NotFundException(['msg' => '此用户不存在']);
        }

    }

    public function logOut()
    {
        (new CacheTool())->clearCache(config('secure.captcha_key'));
    }

    public function writeDiscuss()
    {
        $param = $this->request->param(['title', 'content']);
        try {
            $this->validate($param,'UserValidate.writer');
        } catch (ValidateException $e) {
            throw new ClientException(['msg' => $e->getMessage()]);
        }

        Discuss::create([
            'title' => $param['title'],
            'content' => $param['content'],
            'author_id' => (new CacheTool())->getCache(config('secure.current_user_key'))
        ]);
    }
}